package com.cdks.wuxiu.api.service;

import lombok.extern.slf4j.Slf4j;

import com.cdks.wuxiu.api.component.constant.Constant;
import com.cdks.wuxiu.api.service.redis.RedisService;
import com.cdks.wuxiu.api.util.SmsUtils;
import com.cdks.wuxiu.common.exception.ApiException;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Slf4j
@Service
public class CommonServiceImpl implements CommonService {
    @Resource
    private RedisService redisService;


    @Override
    public int sendSmsCode(String phone, String code) {
        // 缓存验证码
        redisService.setSmsCode(phone, code);

        // 发送短信
        if (code.equals("000000")) {
            //为了固定验证码不限制次数，先减一次
            redisService.decSmsCount(phone);
            
            throw new ApiException(10, "请输入验证码：" + code);
        } else {
            SmsUtils.sendAuthCode(phone, code);
        }

        return 0;
    }

    @Override
    public int checkSmsCode(String phone, String code) {
        String smsCode   = redisService.getSmsCode(phone);
        if (!code.equals(smsCode)) {
            throw new ApiException(10, "验证码错误");
        }

        return 0;
    }

    /**
     * 检查手机号获取验证码的次数限制
     */
    @Override
    public int checkSmsCount(String phone) {
        int count  = redisService.addSmsCount(phone);
        if (count > Constant.SMS_TIMES_LIMIT)
        {
            throw new ApiException(10, "验证码获取次数超限");
        }

        return 0;
    }
}
